package com.kgcx.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.kgcx.common.bean.ReturnData;
import com.kgcx.gateway.api.ApiUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ContentType;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author 吴刚林
 * @date 2017/12/5
 */
@Component
@Slf4j
public class ApiFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String servletPath = ctx.getRequest().getServletPath();
        if (ApiUtils.notApi(servletPath)) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.SC_OK);
            ctx.getResponse().setContentType(
                    ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8).toString());
            ctx.setResponseBody(JSONObject.toJSONString(new ReturnData<>("-99", "访问路径非合法api，请求被拒绝")));
            log.error("访问路径非app合法api，请求被拒绝.url:" + servletPath);
        }
        return null;
    }
}
